package com.gxgeek.spring.security.securitycore.validate;

import com.gxgeek.spring.security.securitycore.properties.SecurityConstants;
import com.gxgeek.spring.security.securitycore.properties.SecurityProperties;
import com.gxgeek.spring.security.securitycore.validate.code.image.ImageCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 实现  InitializingBean 接口
 * 继承 OncePerRequestFilter 只拦截一次
 * @author gaoxing
 * @create 2017-10-17 下午9:47
 */
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();


    private Set<String> urlSet = new HashSet<>();

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private AuthenticationFailureHandler failureHandler;
    AntPathMatcher pathMatcher =  new AntPathMatcher();



    //初始化完成后调用
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String [] urls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getImage().getUrl(),",");
        urlSet.addAll(Arrays.asList(urls));
        urlSet.add(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean action = false;
        for (String url:urlSet){
            if(pathMatcher.match(url,request.getRequestURI())){
                action = true;
                break;
            }
        }
        if (action
                && StringUtils.endsWithIgnoreCase(request.getMethod(),"post")){
          try {
               validate(new ServletWebRequest(request,response));

          }catch (ValidateCodeException e){
              failureHandler.onAuthenticationFailure(request,response,e);
              return;
          }
        }
        filterChain.doFilter(request,response);
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        ImageCode imageCodeInSession = (ImageCode) sessionStrategy.getAttribute(request,ValidateCodeController.sessionKey);
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "image");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }

        if (codeInRequest == null) {
            throw new ValidateCodeException( "验证码不存在");
        }

        if (imageCodeInSession.isExpried()) {
            sessionStrategy.removeAttribute(request, ValidateCodeController.sessionKey);
            throw new ValidateCodeException( "验证码已过期");
        }

        if (!StringUtils.equals(imageCodeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException( "验证码不匹配");
        }

        sessionStrategy.removeAttribute(request, ValidateCodeController.sessionKey);

    }
}
